package com.dek.seckill.common.mq;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.expression.Maps;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MQConfig {

    public static final String QUEUE = "queue";


    public static final String TOPIC_QUEUE_1 = "topic.queue1";
    public static final String TOPIC_QUEUE_2 = "topic.queue2";
    public static final String ROUTING_KEY1 = "topic.key1";
    public static final String ROUTING_KEY2 = "topic.#";
    public static final String TOPIC_EXCHANGE = "topicExchange";


    public static final String FANOUT_EXCHANGE = "fanoutExchange";


    public static final String HEADERS_EXCHANGE = "headersExchange";
    public static final String HEADER_QUEUE = "header.queue";


    public static final String SECKILL_QUEUE = "seckillQueue";

    /**
     * direct 模式
     */
    @Bean
    public Queue queue() {
        return new Queue(QUEUE, true);
    }

    /**
     * topic 模式
     * msg 1 收到了两次
     */
    @Bean
    public Queue topic1() {
        return new Queue(TOPIC_QUEUE_1, true);
    }

    @Bean
    public Queue topic2() {
        return new Queue(TOPIC_QUEUE_2, true);
    }

    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(TOPIC_EXCHANGE);
    }

    @Bean
    public Binding topicBinding1() {
        return BindingBuilder.bind(topic1()).to(topicExchange()).with(ROUTING_KEY1);
    }

    @Bean
    public Binding topicBinding2() {
        return BindingBuilder.bind(topic2()).to(topicExchange()).with(ROUTING_KEY2);
    }

    /**
     * fanout 模式
     * @return
     */
    @Bean
    public FanoutExchange fanoutExchange() {
        return new FanoutExchange(FANOUT_EXCHANGE);
    }


    @Bean
    public Binding fanoutBinding1() {
        return BindingBuilder.bind(topic1()).to(fanoutExchange());
    }

    @Bean
    public Binding fanoutBinding2() {
        return BindingBuilder.bind(topic2()).to(fanoutExchange());
    }

    /**
     * header 模式
     * @return
     */
    @Bean
    public HeadersExchange headersExchange() {
        return new HeadersExchange(HEADERS_EXCHANGE);
    }

    @Bean
    public Queue headerQueue() {
        return new Queue(HEADER_QUEUE, true);
    }

    @Bean
    public Binding headerBinding() {
        Map<String, Object> map = new HashMap<>();
        map.put("header1", "val1");
        map.put("header2", "val2");
        return BindingBuilder.bind(headerQueue()).to(headersExchange()).whereAll(map).match();
    }

    /**
     * direct 模式
     */
    @Bean
    public Queue seckillQueue() {
        return new Queue(SECKILL_QUEUE, true);
    }

}
